package com.siyoumi.app.modules.mall2.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.siyoumi.app.entity.M2Group;
import com.siyoumi.app.service.M2GroupService;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.exception.XException;
import com.siyoumi.service.IWebService;
import com.siyoumi.util.XReturn;
import com.siyoumi.component.XSpringContext;
import com.siyoumi.util.XStr;
import com.siyoumi.component.http.InputData;
import com.siyoumi.component.http.XHttpContext;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SvcM2Group
        implements IWebService {
    static public SvcM2Group getBean() {
        return XSpringContext.getBean(SvcM2Group.class);
    }

    static public M2GroupService getApp() {
        return M2GroupService.getBean();
    }

    /**
     * select
     *
     * @return query
     */
    public QueryWrapper<M2Group> listQuery(InputData inputData) {
        String groupName = inputData.input("group_name");

        QueryWrapper<M2Group> query = getApp().q();
        query.eq("mgroup_x_id", XHttpContext.getX());
        //排序
        query.orderByAsc("mgroup_order")
                .orderByDesc("mgroup_create_date");
        if (XStr.hasAnyText(groupName)) //名称
        {
            query.like("mgroup_name", groupName);
        }

        return query;
    }


    /**
     * 删除
     *
     * @return
     */
    @SneakyThrows
    @Transactional(propagation = Propagation.MANDATORY)
    public XReturn delete(List<String> ids) {
        XReturn r = XReturn.getR(0);

        InputData inputData = InputData.getIns();
        QueryWrapper<M2Group> query = listQuery(inputData);
        query.in("mgroup_id", ids);

        SvcM2Spu appSpu = SvcM2Spu.getBean();

        List<M2Group> list = getApp().get(query);
        for (M2Group entity : list) {
            Long count = appSpu.getCount(entity.getKey());
            if (count > 0) {
                XReturn rDel = EnumSys.API_ERROR.getR("清空" + entity.getMgroup_name() + "分组商品，才能进行删除操作");
                throw new XException(rDel);
            }

            getApp().removeById(entity);
        }

        return r;
    }
}
